import { Component, OnInit } from '@angular/core';
import { AxiosService } from '../../axios.service';
import { DatePipe } from '@angular/common';

import { LocalStorageService } from 'src/app/myService/local-storage.service';
import { ExceljsService } from './../../myService/exceljs.service';




@Component({
  selector: 'app-wuliaofafang',
  templateUrl: './wuliaofafang.component.html',
  styleUrls: ['./wuliaofafang.component.scss'],
  providers: [DatePipe]

})
export class WuliaofafangComponent implements OnInit {
  isSendVisible = false;
  listOfData = [];
  switchValue = false;
  searchValue = ''; //筛选框输入的内容
  searchValue2 = ''; //筛选框输入的内容、
  index = 1;//页数
  max;//总页数
  llre;
  listdata = [];//一页的数据
  NGnum;//退库数量
  tksl;
  OKnum;//已备数量
  ybsl;
  checkResult;//插件  是否展示
  id;
  box;
  xykc;//现有库存
  xqzl;//需求总量
  bzj;
  radioValue = 'All'; // 默认筛选
  radioValue2 = 'All'; // 默认筛选
  radioValue3;
  style = {
    display: 'block',
    height: '35px',
    width: '130px',
    lineHeight: '35px',
    padding: '0px 15px'
  };
  checkResult2;//已备状态修改 是否显示
  checkResult3;//退库
  checkResult4;//领料时间
  liliaos;//领料时间
  lldata;//领料这条数据
  xgdjh;// 修改状态单据号
  xglh;//修改状态  show 料号
  ztid;//修改状态  id
  cnclist;
  radioValue4;
  exportList = []; // 下载
  radioValuebb = "";
  startValue6 = "";
  endValue6 = "";
  searchValuexh = "";
  startValue1 = "";
  checkResult5;
  checkResult6;
  allbox = false;
  allrentime = false;
  alldjh;
  engineerData;
  engineerData2;
  engineerDataCheckBoox;
  engineerDataCheckBoox2;
  checkResult7 = false;
  px;
  yibeishuliang;
  tuidan1;
  juj = false;
  progressValue: number = 0;//进度条数值
  progressStatus: string = 'active';//进度条的状态
  isShowForProgress = false;//是否显示进度条
  loadingText = '下载中，请稍后';
  ellipsisCount = 0;
  timer: any;

  constructor(
    public axios: AxiosService,
    private storage: LocalStorageService,
    public excel: ExceljsService,
    private datePipe: DatePipe,

  ) { }

  ngOnInit(): void {
    this.axios.axiosPost('QueryCncInfo', { status: "" }).then((date) => {
      console.log(date)
      this.cnclist = date["order"]
    })
    this.getalllist(this.index);
  }

  // 获取表格数据
  getalllist(index) {
    var aaa = "";
    if (this.radioValue4) {
      aaa = this.radioValue4.substring(0, 1)
    }
    this.listdata = [];//一页的数据
    console.log("状态", this.radioValue)
    console.log("类型", this.radioValue2)
    console.log("机台号", aaa)
    console.log("工单号", this.searchValue)
    console.log("料号", this.searchValue2)
    console.log("班次", this.radioValuebb)
    console.log("箱号", this.searchValuexh)
    console.log("加工日期", this.startValue1)



    this.axios.axiosPost("QueryMaterialSend", { order: this.px, status: this.radioValue, type: this.radioValue2, cnc: aaa, unionorder: this.searchValue, material_no: this.searchValue2, banci: this.radioValuebb, box: this.searchValuexh, jiagongriqi: this.startValue1, tuidan: this.tuidan1 }).then((date) => {
      console.log(date)
      if (date["result"] == "ok") {
        this.listOfData = date["order"]
        // console.log(this.listOfData.length % 12)
        // 判断总页数
        if (this.listOfData.length < 12) {
          this.max = 1;
        } else if (this.listOfData.length % 12 != 0) {
          this.max = (this.listOfData.length - this.listOfData.length % 12) / 12 + 1;
        } else {
          this.max = this.listOfData.length / 12;
        }
        // console.log(this.max, "总页数")
        console.log(this.listOfData)
        // 当前页面战展示数据
        for (var i = 0; i < this.listOfData.length; i++) {
          if (i >= (index - 1) * 12 && i < index * 12) {
            this.listdata.push(this.listOfData[i])
          }
        }
        console.log(this.listdata)

      }
    })
  }

  //送出按钮
  send() {
    this.isSendVisible = true;
  }

  // 赛选  备料状态
  doingForm() {
    this.index = 1;
    this.getalllist(this.index)
  }

  search() {
    this.index = 1;
    this.getalllist(this.index)
  }
  reset() {
    this.searchValue = '';
    this.search();
  }
  StartChange1(a) {
    this.startValue1 = this.datePipe.transform(this.startValue1, 'yyyy-MM-dd');

    this.index = 1;
    this.getalllist(this.index)
    console.log(this.startValue1)
  }
  //箱号筛选
  search2() {
    this.index = 1;
    this.getalllist(this.index)
  }
  reset2() {
    this.searchValue2 = '';
    this.search2();
  }
  reset3() {
    this.searchValuexh = '';
    this.search2();
  }
  // 上一页
  showPrePage() {
    console.log("上一页")
    if (this.index >= 2) {
      this.listdata = [];
      this.index--;
      // 当前页面战展示数据
      for (var i = 0; i < this.listOfData.length; i++) {
        if (i >= (this.index - 1) * 12 && i < this.index * 12) {
          this.listdata.push(this.listOfData[i])
        }
      }
    }

  }
  // 下一頁
  showNextPage() {
    console.log("下一页")
    if (this.index <= this.max - 1) {
      this.listdata = [];
      this.index++;
      // 当前页面战展示数据
      for (var i = 0; i < this.listOfData.length; i++) {
        if (i >= (this.index - 1) * 12 && i < this.index * 12) {
          this.listdata.push(this.listOfData[i])
        }
      }

    }
  }
  // 修改页数
  onChangePage(value) {
    console.log(value)
    if (this.max >= value && value > 0) {
      this.listdata = [];
      this.index = value;
      console.log(value)
      // 当前页面战展示数据
      for (var i = 0; i < this.listOfData.length; i++) {
        if (i >= (this.index - 1) * 12 && i < this.index * 12) {
          this.listdata.push(this.listOfData[i])
        }
      }
    } else {
      alert("没有当前页，当前数据占" + this.max + "页")
    }
  }


  // 修改已备数量---点击
  addsl(item) {
    console.log(item)
    this.checkResult = true;
    // 已备数量  实际
    this.ybsl = item.yibei_shuliang;
    // 当前选中的 id
    this.id = item.id;
    // 现有的库存
    this.xykc = item.stock;
    // 需求总量
    this.xqzl = item.quatity_total
    // 加工件 标准件
    this.bzj = item.type_flag;

    this.OKnum = item.yibei_shuliang
  }
  // 修改退库数量----点击
  addsl2(item) {
    console.log(item)
    this.checkResult3 = true;
    // 当前选中的 id
    this.id = item.id;
    // 现有的库存
    this.xykc = item.stock;
    // 退库数量  实际
    this.tksl = item.tuiku_shuliang;
    this.NGnum = item.tuiku_shuliang

    // 已备数量
    this.ybsl = item.yibei_shuliang;

  };
  // 修改退库 -- 确定
  addCheckResult3() {
    this.checkResult3 = false;
    console.log("输入退库数量:" + this.NGnum)
    console.log("退库初始值为:" + this.tksl)
    console.log("已备数量:" + this.ybsl)
    console.log("库存总量:" + this.xykc)
    //  1.判断当前值是否为空  或者是否修改过
    if (this.NGnum != "" || this.NGnum != this.tksl) {
      console.log("退库数量输入不为空,且进行了修改")
      if (this.ybsl && this.NGnum <= this.ybsl) {
        console.log("输入退库数量小于已备数量")
        // 现有库存 = 实际库存 - 实际退库 + 输入退库数量
        if (this.xykc) {
          this.xykc = Number(this.xykc) - Number(this.tksl) + Number(this.NGnum)
        } else {
          this.xykc = this.NGnum;
        }
        console.log("id", this.id)
        console.log("输入退库数量:", this.NGnum)
        console.log("保存的库存数量:", this.xykc)
        this.axios.axiosPost("UpdateMaterialSend", { id: this.id, tuiku_shuliang: this.NGnum, "stock": this.xykc }).then((data) => {
          console.log(data)
          this.getalllist(this.index);
        })
      } else {
        alert("退库数量不能大于已备数量")
      }


    }


    // 更新当前数据
  }
  // 修改退库--取消
  CancelAddResult3() {
    this.checkResult3 = false;
  };

  // 修改已备--取消
  CancelAddResult() {
    this.checkResult = false;
  }

  // 修改已备 -- 确定
  addCheckResult() {
    this.checkResult = false;
    //  1. 先判断值是否为空  或者 未修改
    console.log("实际已备数量:" + this.ybsl)
    console.log("输入已备数量:" + this.OKnum)
    console.log("现有库存:" + this.xykc)
    if (this.OKnum > 0) {
      if (this.OKnum != "" && this.OKnum != this.ybsl) {
        console.log("输入值不为空,且进行了修改")
        // 2.判断这个值库存是否够用
        if (this.OKnum - this.ybsl <= this.xykc) {
          console.log("现有库存够用")
          // 计算剩余库存
          // 现有库存  =  现有库存实际  - 输入备数量 + 前实际已备数量
          this.xykc = this.xykc - this.OKnum + Number(this.ybsl)
          console.log("输入已备数量", this.OKnum)
          console.log("计算后库存", this.xykc)
          // 3.判断这个值是否为加工件
          if (this.bzj == 0) {
            // 修改已备数量   库存数量
            console.log("这个是标准件")
            if (this.OKnum <= this.xqzl) {
              console.log("已备数量小于的等于需求总量")
              this.axios.axiosPost("UpdateMaterialSend", { id: this.id, "yibei_shuliang": this.OKnum, "stock": this.xykc }).then((data) => {
                if (data["result"] == "ok") {
                  // 4.判断是否大于需求总量
                  if (this.OKnum >= this.xqzl) {
                    // 大于修改状态
                    console.log("ok数量大于需求总量,修改状态为已备料")
                    this.axios.axiosPost("UpdateMaterialSend", { id: this.id, beiliao_ztai: 2 }).then((data) => {
                      if (data["result"] == "ok") {
                        console.log(data)
                        this.getalllist(this.index);

                      }

                    })
                  } else {
                    if (this.xykc <= 0 || !this.xykc) {
                      if (this.OKnum >= this.xqzl) {
                        console.log("ok数量大于需求总量,修改状态为已备料")
                        this.axios.axiosPost("UpdateMaterialSend", { id: this.id, beiliao_ztai: 2 }).then((data) => {
                          if (data["result"] == "ok") {
                            this.getalllist(this.index);
                          }

                        })
                      } else {
                        this.axios.axiosPost("UpdateMaterialSend", { id: this.id, beiliao_ztai: 3 }).then((data) => {
                          console.log("现有库存小于等于0,修改状态为缺料")
                          if (data["result"] == "ok") {
                            this.getalllist(this.index);
                          }
                        })
                      }

                    } else {
                      // 小于修改状态
                      this.axios.axiosPost("UpdateMaterialSend", { id: this.id, beiliao_ztai: 1 }).then((data) => {
                        console.log("ok数量小于需求总量,且内存不为0,修改状态为备料中")
                        if (data["result"] == "ok") {
                          this.getalllist(this.index);
                        }

                      })
                    }

                  }
                }
                console.log(data)
              })

            } else {
              alert("標準件已備數量不能大於需求總量")
            }
            console.log("id:" + this.id)
            console.log("输入已备数量:" + this.OKnum)
            console.log("存储现有库存:" + this.xykc)

          } else {
            // 修改已备数量  和 库存总数
            console.log("这个是加工件或者领用单")
            console.log("id" + this.id)
            console.log("输入已备数量:" + this.OKnum)
            console.log("存储现有库存:" + this.xykc)
            this.axios.axiosPost("UpdateMaterialSend", { id: this.id, "yibei_shuliang": this.OKnum, "stock": this.xykc }).then((data) => {
              console.log(data)
              if (data["result"] == "ok") {
                this.getalllist(this.index);

              }
            })

          }
        } else {
          // 2.库存小于填写的值
          alert("库存不足")
        }
      }
    } else {
      alert("已備數量不能為負值")
    }

  }
  xgxh(item) {
    if (item.type_flag == 0) {
      this.allbox = false;
      console.log(item)
      this.box = item.box;
      this.id = item.id;
      this.alldjh = item;
      this.checkResult5 = true;
    } else {
      alert("此筆數據非標準件")
    }
  }
  addCheckResult5() {
    console.log(this.id, this.box, this.allbox)
    if (this.allbox == false) {
      this.axios.axiosPost("UpdateMaterialSend", { id: this.id, box: this.box }).then((data) => {
        console.log(data)
        this.getalllist(this.index);
        this.checkResult5 = false;
      })
    } else {
      if (this.box) {
        this.checkResult5 = false;
        this.checkResult6 = true;
        console.log(this.alldjh.union_order);
        console.log(this.box);

        this.axios.axiosPost("QueryMaterialSend", { unionorder: this.alldjh.union_order, type: "2" }).then((data) => {
          console.log(data);
          if (data["result"] == "ok") {
            this.engineerDataCheckBoox = [];
            this.engineerData = data["order"]
            for (let i = 0; i < this.engineerData.length; i++) {
              if (this.engineerData[i].beiliao_ztai == 2 && this.engineerData[i].box == "") {
                this.engineerDataCheckBoox[i] = true;
              } else {
                this.engineerDataCheckBoox[i] = false;
              }
            }

          }

        })
      } else {
        alert("未填寫箱號")
      }

    }
  };
  CancelAddResult5() {
    this.checkResult5 = false;
  }
  addCheckResult6() {
    let list = [];
    for (let i = 0; i < this.engineerDataCheckBoox.length; i++) {
      if (this.engineerDataCheckBoox[i] == true) {
        list.push(this.engineerData[i])
      }
    }
    console.log(this.box, list);
    if (list.length == 0) {
      alert("至少選擇一個工件")
    } else {
      this.axios.axiosPost("UpdateMaterialSend", { "box": this.box, "list": list }).then((data) => {
        console.log(data);
        if (data["result"] == "ok") {
          this.checkResult6 = false;
          this.getalllist(1);
        }
      })
    }


  }
  CancelAddResult6() {
    this.checkResult6 = false;

  }
  // 加工件更改状态
  gbzt(item) {

    if (item.type_flag == 1 || item.type_flag == 2) {
      this.checkResult2 = true;
      this.xgdjh = item.union_order
      this.xglh = item.material_no
      this.ztid = item.id;
      if (item.type_flag == 2) {
        this.juj = true;
      } else {
        this.juj = false;
      }
      if (item.beiliao_ztai == 1) {
        this.radioValue3 = "備料中"
      } else if (item.beiliao_ztai == 2) {
        this.radioValue3 = "已備料"
      } else {
        this.radioValue3 = "缺料"
      }
    }
  }
  // 加工件更改状态--确认
  addCheckResult2() {
    this.checkResult2 = false;
    console.log(this.ztid)
    console.log(this.radioValue3)
    if (this.radioValue3 == "備料中") {
      this.axios.axiosPost("UpdateMaterialSend", { id: this.ztid, "beiliao_ztai": 1 }).then((data) => {
        console.log(data)
        this.getalllist(this.index);
      })

    } else if (this.radioValue3 == "已備料") {
      this.axios.axiosPost("UpdateMaterialSend", { id: this.ztid, "beiliao_ztai": 2 }).then((data) => {
        console.log(data)
        this.getalllist(this.index);
      })

    } else if (this.radioValue3 == "缺料") {
      this.axios.axiosPost("UpdateMaterialSend", { id: this.ztid, "beiliao_ztai": 3 }).then((data) => {
        console.log(data)
        this.getalllist(this.index);
      })
    } else if (this.radioValue3 == "拒絕") {
      // console.log(this.ztid.toString().substring(2, this.ztid.length));

      this.axios.axiosPost('UpdateMaterialApply', { id: this.ztid.toString().substring(2, this.ztid.length), status: false }).then((data) => {
        console.log(
          data
        );
        this.getalllist(this.index);
      })
    }
  }
  // 加工件更改状态--取消
  CancelAddResult2() {
    this.checkResult2 = false;
  }
  // 领料时间
  lltime(item) {
    console.log(item);

    this.checkResult4 = true;
    this.lldata = item;
    var n = new Date().getFullYear();
    var y = (new Date().getMonth() + 1).toString();
    y = Number(y) < 10 ? ("0" + y) : y;
    var r = new Date().getDate().toString();
    r = Number(r) < 10 ? ("0" + r) : r;
    this.liliaos = n + "-" + y + "-" + r;
    console.log(this.liliaos)
    this.llre = item.lingliao_ren;
    this.id = item.id;
    this.alldjh = item;
    this.yibeishuliang = item.yibei_shuliang;
  }
  // 领料时间--确认
  addCheckResult4() {
    if (this.allrentime == false) {
      this.checkResult4 = false;
      if (Number(this.yibeishuliang) >= 0) {
        // 当前状态为已备  就可以添加领料时间
        if (this.llre) {
          if (this.lldata.beiliao_ztai == 2) {
            this.axios.axiosPost("UpdateMaterialSend", { id: this.lldata.id, lingliao_riqi: this.liliaos, "lingliao_ren": this.llre }).then((data) => {
              console.log(data)
              this.getalllist(this.index);
            })
          } else {
            alert("當前工件狀態不可領")
          }
        } else {
          alert("未填寫領料人")
        }
      } else {
        alert("未填寫已備數量")
      }

    } else {
      if (Number(this.yibeishuliang) >= 0) {

        if (this.llre) {
          this.axios.axiosPost("QueryMaterialSend", { unionorder: this.alldjh.union_order }).then((data) => {
            console.log(data);
            if (data["result"] == "ok") {
              this.engineerDataCheckBoox2 = [];
              this.engineerData2 = data["order"]
              for (let i = 0; i < this.engineerData2.length; i++) {
                if (this.engineerData2[i].beiliao_ztai == 2 && this.engineerData2[i].lingliao_ren == "" && this.engineerData2[i].lingliao_riqi == "") {
                  this.engineerDataCheckBoox2[i] = true;
                } else {
                  this.engineerDataCheckBoox2[i] = false;
                }
              }
              this.checkResult7 = true;
            }

          })
        } else {
          alert("未填寫領料人")
        }
      } else {
        alert("未填寫已備數量")
      }
      this.checkResult4 = false;

    }

  }
  addCheckResult7() {
    let list = [];
    for (let i = 0; i < this.engineerDataCheckBoox2.length; i++) {
      if (this.engineerDataCheckBoox2[i] == true) {
        list.push(this.engineerData2[i]);
      }
    }
    console.log(list, this.liliaos, this.llre)
    if (list.length == 0) {
      alert("至少選擇一個工件")
    } else {
      this.axios.axiosPost("UpdateMaterialSend", { "lingliao_riqi": this.liliaos, "lingliao_ren": this.llre, "list": list }).then((data) => {
        console.log(data);
        if (data["result"] == "ok") {
          this.checkResult7 = false;
          this.getalllist(1);
        }
      })
    }
  }
  CancelAddResult7() {
    this.checkResult7 = false;
    this.llre = ""
  }
  // 领料时间--取消
  CancelAddResult4() {
    this.checkResult4 = false;
    this.llre = ""
  }

  selEngineer(key) {
    if (this.engineerDataCheckBoox[key]) {
      this.engineerDataCheckBoox.splice(key, 1, false);
    } else {
      this.engineerDataCheckBoox.splice(key, 1, true);
    }
  }
  selEngineer2(key) {
    if (this.engineerDataCheckBoox2[key]) {
      this.engineerDataCheckBoox2.splice(key, 1, false);
    } else {
      this.engineerDataCheckBoox2.splice(key, 1, true);
    }
  }

  startTimer() {
    this.timer = setInterval(() => {
      this.updateLoadingText();
    }, 1000);
  }

  stopTimer() {
    clearInterval(this.timer);
  }

  updateLoadingText() {
    if (this.ellipsisCount < 3) {
      this.ellipsisCount++;
    } else {
      this.ellipsisCount = 0;
    }

    const dots = '.'.repeat(this.ellipsisCount);
    this.loadingText = `下载中，请稍后${dots}`;
  }

  // 下载报表
  downLoad() {
    this.isShowForProgress = true;
    this.startTimer();
    // this.datePipe.transform(this.startValue1, "yyyy-MM-dd");
    // console.log(this.datePipe.transform(this.startValue6, "yyyy-MM-dd") + "22" + this.endValue6);

    // 下载接口 （后台记录下载次数等信息）
    this.axios.axiosPost('AddDownloadCount')
      .then((data) => {
        console.log(data)
      })
      .catch((err) => {
        console.log(err);
      });

      let increment = 1;
      let interval = setInterval(() => {
        if (this.progressValue < 90) {
            this.progressValue += increment;
          }
      }, 1000);
    // 获取数据
    this.axios.axiosPost('QueryBaobiaoLingyong', {
      starttime: this.datePipe.transform(this.startValue6, "yyyy-MM-dd"),
      endtime: this.datePipe.transform(this.endValue6, "yyyy-MM-dd"),
    })
      .then((data) => {
        this.exportList = data['order'];
        console.log('下载的数据：'+this.exportList,"长度："+this.exportList.length);

        let leo = []
        for (let i = 0; i < this.exportList.length; i++) {
          // this.exportList[i].cost = this.exportList[i].cost;
          // this.exportList[i].cost = this.exportList[i].cost.toFixed(2);
          let arr = {
            a: this.exportList[i].status,
            b: this.exportList[i].lingliao_riqi,
            c: this.exportList[i].date,
            d: this.exportList[i].unionorder,
            e: this.exportList[i].name,
            f: this.exportList[i].machine,
            g: this.exportList[i].xuhao,
            h: this.exportList[i].type,
            i: this.exportList[i].workorder,
            j: this.exportList[i].material_no,
            k: this.exportList[i].material_type,
            l: this.exportList[i].quatity,
            m: this.exportList[i].unit,
            n: this.exportList[i].charge,
            o: this.exportList[i].apply_person,
            p: Number(this.exportList[i].cost).toFixed(2),
            q: this.exportList[i].remark,

          }
          leo.push(arr)
        }
        // 生成excel
        let downList = [];
        leo.forEach((row: any) => {
          console.log(row);
          downList.push(Object.values(row))

        })
        console.log(downList);

        // '狀態', '領料日期',
        let head = ['狀態', '領料日期', '結單日期', '單據號', '治具名稱', '機種', '序號', '類型', '名稱', '料號', '類別', '數量', '單位', '費用charge部門', '領用人', '未稅物料總費用', '備註'];
        let reportData = {
          title: '領用明細',
          data: downList,
          headers: head
        };
        this.excel.exportLingyong(reportData);
      })
      .catch((err) => {
        console.log(err);
        clearInterval(interval);
      })
      .finally(() => {
        // 请求完成
        this.progressValue = 100;
        this.progressStatus = 'success';
        this.loadingText = '下载完成！';
        setTimeout(() => {
           this.isShowForProgress = false;
        },2000)
        // 请求完成后清除定时器
        clearInterval(interval);
        this.stopTimer();
      })
    // 重置变量，方便下次使用
    this.exportList = [];
    this.progressStatus = 'active';
    this.progressValue = 0;
    this.loadingText = '下载中，请稍后';
  }

  sortLjmcASC() {
    this.px = "order by position asc"
    this.getalllist(1)
  }
  sortLjmcDESC() {
    this.px = "order by position desc"
    this.getalllist(1)
  }
  tuidan() {
    console.log(this.switchValue);
    if (this.switchValue) {
      this.tuidan1 = 1
    } else {
      this.tuidan1 = ""
    }
    this.getalllist(this.index)
  }

  validateInput(newValue) {
    console.log(newValue);
    // let regex = /^[1-9]\d*(\.\d+)?$/;
    if (newValue<0) {
      console.log('不是正数！');
      this.OKnum = ''
    }
    // if (newValue.toString().indexOf('-')!==-1) {
    // }
  }
}
